import React, { Component } from 'react'
import './signin.scss'
import {
    Form,
    Input,
    Tooltip,
    Cascader,
    Select,
    Row,
    Col,
    Checkbox,
    Button,
    message,
    Upload,
    Modal
} from 'antd';
import api from '../../api'


import residen from '../../api/residen.json'
import logo from '../../assets/logo.png'
import getBase64 from '../../utils/getBase64'
import icon from '../../config/iconConfig'
import { uploadAction } from '../../constants'
const IconFont = icon.icon()
const { Option } = Select;



export default class Login extends Component {
    state = {
        previewVisible: false, // 标识是否显示大图预览Modal
        previewImage: '', // 大图的url
        fileList: [
            /*{
              uid: '-1', // 每个file都有自己唯一的id
              name: 'xxx.png', // 图片文件名
              status: 'done', // 图片状态: done-已上传, uploading: 正在上传中, removed: 已删除
              url: 'https://zos.alipayobjects.com/rmsportal/jkjgkEfvpUPVyRjUImniVslZfWPnJuuZ.png', // 图片地址
            },*/
        ],
        //身份信息
        residences: [],
        prefixSelector: (
            <Form.Item name="prefix" noStyle>
                <Select
                    style={{
                        width: 70,
                    }}
                >
                    <Option value="86">+86</Option>
                    <Option value="87">+87</Option>
                </Select>
            </Form.Item>
        ),
        formItemLayout : {
            labelCol: {
              xs: {
                span: 24,
              },
              sm: {
                span: 8,
              },
            },
            wrapperCol: {
              xs: {
                span: 24,
              },
              sm: {
                span: 16,
              },
            },
          },
          tailFormItemLayout : {
            wrapperCol: {
              xs: {
                span: 24,
                offset: 0,
              },
              sm: {
                span: 16,
                offset: 8,
              },
            },
          }
    }
    //处理表单数据
    handleSubmit = (values) => {
        const {fileList } = this.state
        let time = new Date().toLocaleString();
        console.log(time);
        console.log('Received values of form: ', values);
        values = { ...values,avatar:fileList[0]?fileList[0].url:'' }
        api.signin.sign(values,time).then(res=>{
            console.log(res);
            if(res.data.msg){
                message.error(res.data.msg);
            }
            if(res.data.data){
                message.success("注册成功");
            }
        })
    }
       /*
  获取所有已上传图片文件名的数组
   */
  getImgs  = () => {
    return this.state.fileList.map(file => file.name)
  }

  /*
  隐藏Modal
   */
  handleCancel = () => this.setState({ previewVisible: false });

  handlePreview = async file => {
    console.log('handlePreview()', file)
    if (!file.url && !file.preview) {
        file.preview = await getBase64.getBase64(file.originFileObj);
      }
    // 显示指定file对应的大图
    this.setState({
      previewImage: file.url || file.thumbUrl,
      previewVisible: true,
    });
  };
  /*
  file: 当前操作的图片文件(上传/删除)
  fileList: 所有已上传图片文件对象的数组
   */
  handleChange = async ({ file, fileList }) => {
    console.log('handleChange()', file.status, fileList.length, file===fileList[fileList.length-1])

    // 一旦上传成功, 将当前上传的file的信息修正(name, url)
    if(file.status==='done') {
      const result = file.response  // {status: 0, data: {name: 'xxx.jpg', url: '图片地址'}}
      if(result.status===0) {
        message.success('上传图片成功!')
        const {name, url} = result.data
        file = fileList[fileList.length-1]
        file.name = name
        file.url = url
      } else {
        message.error('上传图片失败')
      }
    } else if (file.status==='removed') { // 删除图片
      const result = await api.user.reqDeleteImg(file.name)
      console.log(result);
      if (result.data.status===0) {
        message.success('删除图片成功!')
      } else {
        message.error('删除图片失败!')
      }
    }

    // 在操作(上传/删除)过程中更新fileList状态
    this.setState({ fileList })
  };
    componentDidMount(){
        console.log(residen);
        const {residences} = this.state
        this.setState({residences:residen.provinces.province})
    }
    render() {
        
        const {residences,prefixSelector,formItemLayout,tailFormItemLayout,previewVisible,previewImage,fileList} = this.state
        const uploadButton = (
            <div>
              <IconFont type="icon-zengjiatianjiajiajian" />
              <div>Upload</div>
            </div>
          );
        return (
            <div id="login">
                <header className="flex_start">
                    <div className="logo"><img src={logo} alt="" /></div>
                    <p className="title">金皮卡：后台管理系统</p>
                </header>
                <section>
                    <div className="bk"></div>
                    <div className="login-content">
                        <h2>用户注册</h2>
                        <Form
                        {...formItemLayout}
                            name="register"
                            onFinish={this.handleSubmit}
                            initialValues={{
                                residence: ['浙江省', '杭州市', '余杭区'],
                                prefix: '86',
                            }}
                        >
                            <Form.Item
                                name="email"
                                label="E-mail"
                                rules={[
                                    {
                                        type: 'email',
                                        message: '邮箱格式不正确!',
                                    },
                                    {
                                        required: true,
                                        message: '请输入邮箱号!',
                                    },
                                ]}
                            >
                                <Input />
                            </Form.Item>
                            <Form.Item
                                name="phone"
                                label="电话号码"
                                rules={[
                                    {
                                        required: true,
                                        message: '请输入电话号码!',
                                    },
                                    {
                                        max:11,
                                        message:'请输入正确的电话号码'
                                    },
                                    {
                                        pattern: /^[0-9]+$/, 
                                        message:'请输入正确的电话号码'
                                    }
                                ]}
                            >
                                <Input
                                    addonBefore={prefixSelector}
                                    style={{
                                        width: '100%',
                                    }}
                                />
                            </Form.Item>
                            <Form.Item
                                name="password"
                                label="密码"
                                rules={[
                                    {
                                        required: true,
                                        message: '请输入密码!',
                                    },
                                    {
                                        pattern: /^[a-zA-Z]\w{5,17}$/, 
                                        message: '以字母开头，长度在6~18之间，不包含特殊字符，18之间，不包含特殊字符，可以使用下划线!',
                                    },
                                ]}
                                help="以字母开头，长度在6~18之间，不包含特殊字符，可以使用下划线"
                            >
                                <Input.Password />
                            </Form.Item>

                            <Form.Item
                                name="confirm"
                                label="确认密码"
                                dependencies={['password']}
                                rules={[
                                    {
                                        required: true,
                                        message: '请确认密码!',
                                    },
                                    ({ getFieldValue }) => ({
                                        validator(_, value) {
                                            if (!value || getFieldValue('password') === value) {
                                                return Promise.resolve();
                                            }

                                            return Promise.reject('两次密码不相同!');
                                        },
                                    }),
                                ]}
                            >
                                <Input.Password />
                            </Form.Item>

                            <Form.Item
                                name="nickname"
                                label={
                                    <span>
                                        昵称&nbsp;
                                        <Tooltip title="别的名称去称呼你?也是唯一的">
                                            <IconFont type="icon-bangzhu" />
                                        </Tooltip>
                                    </span>
                                }
                                rules={[
                                    {
                                        required: true,
                                        message: '请输入昵称!',
                                        whitespace: true,
                                    },
                                ]}
                            >
                                <Input />
                            </Form.Item>

                            <Form.Item
                                name="residence"
                                label="所在地区"
                                rules={[
                                    {
                                        type: 'array',
                                        required: true,
                                        message: '选择所在地区!',
                                    },
                                ]}
                            >
                                <Cascader  fieldNames={{ label: 'ssqname', value: 'ssqname'}} options={residences} />
                            </Form.Item>
                            <Form.Item
                        label="头像设置"
                        rules={[
                            {
                                required: true,
                                message: '设置头像!',
                            },
                        ]}
                    >
                        <Upload
                            action={uploadAction} /*上传图片的接口地址*/
                            accept='image/*'  /*只接收图片格式*/
                            name="avatar"
                            listType="picture-card"  /*卡片样式*/
                            fileList={fileList}  /*所有已上传图片文件对象的数组*/
                            onPreview={this.handlePreview}
                            onChange={this.handleChange}
                        >
                            {fileList.length >= 1? null : uploadButton}
                        </Upload>
                        <Modal visible={previewVisible} footer={null} onCancel={this.handleCancel}>
                            <img alt="example" style={{ width: '100%' }} src={previewImage} />
                        </Modal>
                    </Form.Item>
                            

                            <Form.Item
                                name="agreement"
                                valuePropName="checked"
                                rules={[
                                    // {
                                    //     validator: (_, value) =>
                                    //         value ? Promise.resolve() : Promise.reject('Should accept agreement'),
                                    // },
                                ]}
                                {...tailFormItemLayout}
                            >
                                <Checkbox>
                                    I have read the <a href="">agreement</a>
                                </Checkbox>
                            </Form.Item>
                            <Form.Item {...tailFormItemLayout}>
                                <Button type="primary" htmlType="submit">注册</Button>
                            </Form.Item>
                        </Form>
                    </div>

                </section>
            </div>
        )
    }
}
